package suanfa;

public class swapPairs {
    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
    public ListNode swapPairs(ListNode head) {
        if(head==null || head.next==null) return head;
        ListNode newHead=new ListNode(0);
        newHead.next=head;
        ListNode prev=newHead,cur=prev.next,next=cur.next,nnext=next.next;
        while(cur!=null && next!=null){
            //1.交换节点
            prev.next=next;
            next.next=cur;
            cur.next=nnext;
            //2.修改指针
            prev=cur;
            cur=nnext;
            if(cur!=null) next=cur.next;
            if(next!= null) nnext=next.next;
        }
        return newHead.next;
    }
}
